package algorithm

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"b2c-delivery-optimization/internal/model"
)

// WaveAllocationValidator 波次分配验证器
type WaveAllocationValidator struct {
	visualService *VisualizationService
	outputDir     string
}

// NewWaveAllocationValidator 创建波次分配验证器
func NewWaveAllocationValidator(outputDir string) *WaveAllocationValidator {
	return &WaveAllocationValidator{
		visualService: NewVisualizationService(outputDir),
		outputDir:     outputDir,
	}
}

// ValidateAllocation 验证波次分配结果
func (v *WaveAllocationValidator) ValidateAllocation(waveOrders [][]model.Order, metrics []AlgorithmMetrics) error {
	if len(waveOrders) == 0 {
		return fmt.Errorf("波次订单数据为空")
	}

	fmt.Printf("开始验证波次分配结果，波次数: %d\n", len(waveOrders))

	// 创建输出目录
	if err := os.MkdirAll(v.outputDir, 0755); err != nil {
		return fmt.Errorf("创建输出目录失败: %v", err)
	}

	// 验证波次数据
	totalOrders := 0
	for i, wave := range waveOrders {
		if len(wave) == 0 {
			return fmt.Errorf("波次 %d 没有订单", i+1)
		}
		fmt.Printf("波次 %d 包含 %d 个订单\n", i+1, len(wave))
		totalOrders += len(wave)
	}

	if totalOrders == 0 {
		return fmt.Errorf("所有波次的总订单数为0")
	}

	fmt.Printf("波次验证完成，总订单数: %d\n", totalOrders)

	// 生成所有图表
	fmt.Println("开始生成图表...")
	if err := v.visualService.GenerateCharts(waveOrders, metrics); err != nil {
		return fmt.Errorf("生成图表失败: %v", err)
	}
	fmt.Println("图表生成完成")

	// 生成验证报告
	report := v.generateReport(waveOrders, metrics)
	if err := v.saveReport(report); err != nil {
		return fmt.Errorf("保存验证报告失败: %v", err)
	}
	fmt.Println("验证报告已保存")

	return nil
}

// generateReport 生成验证报告
func (v *WaveAllocationValidator) generateReport(waveOrders [][]model.Order, metrics []AlgorithmMetrics) string {
	var report string

	// 添加报告头部
	report += fmt.Sprintf("波次分配验证报告\n")
	report += fmt.Sprintf("生成时间: %s\n\n", time.Now().Format("2006-01-02 15:04:05"))

	// 添加波次统计信息
	report += "波次统计:\n"
	for i, orders := range waveOrders {
		report += fmt.Sprintf("波次%d: %d个订单\n", i+1, len(orders))
	}
	report += "\n"

	// 添加算法指标信息
	if len(metrics) > 0 {
		lastMetric := metrics[len(metrics)-1]
		report += "算法指标:\n"
		report += fmt.Sprintf("优先级得分: %.2f\n", lastMetric.PriorityScore)
		report += fmt.Sprintf("位置得分: %.2f\n", lastMetric.LocationScore)
		report += fmt.Sprintf("平衡得分: %.2f\n", lastMetric.BalanceScore)
	}

	// 添加图表文件路径
	report += "\n图表文件:\n"
	report += fmt.Sprintf("波次分布图: %s\n", v.visualService.GetChartPath(WaveChart))
	report += fmt.Sprintf("优先级分布图: %s\n", v.visualService.GetChartPath(PriorityChart))
	report += fmt.Sprintf("位置分布图: %s\n", v.visualService.GetChartPath(LocationChart))
	report += fmt.Sprintf("算法指标图: %s\n", v.visualService.GetChartPath(MetricsChart))

	return report
}

// saveReport 保存验证报告
func (v *WaveAllocationValidator) saveReport(report string) error {
	filepath := filepath.Join(v.outputDir, "validation_report.txt")
	return os.WriteFile(filepath, []byte(report), 0644)
}
